package com.kevin.data.batch.component;

import com.kevin.data.batch.configuration.BizItemProcessor;
import com.kevin.data.batch.configuration.BizJobListener;
import com.kevin.data.batch.model.Log;
import jakarta.annotation.Resource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * CSV 读写处理
 */
@Component
public class CsvBatchComponent {

    @Resource
    private JobRepository jobRepository;

    @Resource
    private BizJobListener jobListener;

    @Resource
    private BizItemProcessor bizItemProcessor;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Bean("csvJob")
    public Job csvJob() {
        return new JobBuilder("csvJob", jobRepository).start(csvStep()).listener(jobListener).build();
    }

    private Step csvStep() {
        return new StepBuilder("csvStep", jobRepository).<Log, Log>chunk(3, transactionManager).reader(csvItemReader())
                .processor(bizItemProcessor) // 按需实现处理逻辑
                .writer(list -> list.forEach(data -> System.err.println("csvItemReader : " + data)))
                .allowStartIfComplete(true).build();
    }

    private FlatFileItemReader<Log> csvItemReader() {
        FlatFileItemReader<Log> csvReader = new FlatFileItemReader<>();
        // 文件路径
        csvReader.setResource(new ClassPathResource("data/log.csv"));
        // 第一行表头处理
        csvReader.setLinesToSkip(1);
        csvReader.setLineMapper(new DefaultLineMapper<>() {{
            setLineTokenizer(new DelimitedLineTokenizer() {{
                setNames("id", "description", "method", "remoteAddr", "userAgent", "clientId");
            }});
            setFieldSetMapper(new BeanWrapperFieldSetMapper<>() {{
                setTargetType(Log.class);
            }});
        }});
        return csvReader;
    }

}
